package com.accp.hotevent.websocket;

import com.accp.hotevent.entity.Notice;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

@Component
@ServerEndpoint("/notice/{userId}")
@Slf4j
public class NoticeServer {

    private static HashMap<Integer, Session> map = new HashMap<>();
    ObjectMapper objectMapper = new ObjectMapper();
    @OnOpen
    public void handleOpen(Session session, @PathParam("userId") Integer userId) {
        map.put(userId, session);
        log.info("Client is now connected... {} 当前连接数：{}",session.getId(),map.size());
        log.info("userId:{}",userId);
    }

    @OnClose
    public void handleClose(Session session) {
        log.info("Client is now disconnected... {}",session.getId());
        try {
            session.close();
            Iterator<Integer> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                Integer userId = iterator.next();
                Session s = map.get(userId);
                if (!s.isOpen()) {
                    iterator.remove();
                    log.info("userId:{} sid:{}  关闭连接",userId,s.getId());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void sendInfo(Notice notice) {
        Session session = map.get(notice.getUserId());
        try {
            if(session == null){
                log.info("用户还没有上线");
            }else if(session.isOpen()) {
                session.getBasicRemote().sendText(objectMapper.writeValueAsString(notice));
            }
        } catch (IOException e) {
            log.error("推送消息失败：{}，内容：{}", session.getId(), notice);
        }
    }
}
